<template>
  <el-form :model="model" :rules="rules" ref="commonForm" v-bind="formAttrs">
    <el-form-item
      v-for="itemInfo in formInfos"
      v-bind="itemInfo.formItemAttrs"
      :key="itemInfo.id"
      :prop="itemInfo.prop"
    >
      <component
        v-model="model[itemInfo.prop]"
        :is="itemInfo.name"
        :input-info="itemInfo"
      />
    </el-form-item>
    <el-form v-bind="formAttrs">
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button type="primary" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-form>
</template>

<script>
import { defineComponent, ref, getCurrentInstance } from "vue";

export default defineComponent({
  name: "CommonForm",
  props: {
    formInfos: {
      type: Array,
      default: [],
    },
    formAttrs: {
      type: Object,
      default: {},
    },
  },
  setup(props, { emit }) {
    let model = {},
      rules = {};

    props.formInfos.forEach((item) => {
      model[item.prop] = item.value;
      rules[item.prop] = item.rule;
    });

    let commonForm = ref(null);
    const { proxy } = getCurrentInstance();

    //提交表单
    const submitForm = () => {
      proxy.$refs.commonForm.validate((valid) => {
        if (valid) {
          emit("submit", model);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    };
    //重置表单
    const resetForm = () => {
      proxy.$refs.commonForm.resetFields();
    };

    return {
      model: ref(model),
      rules,
      refForm: ref(null),
      commonForm,
      submitForm,
      resetForm,
    };
  },
});
</script>

<style>
</style>